// pages/movies/more-movie/more-movie.js
var app = getApp()
var util = require('../../../utils/uitl.js')
Page({
  data: {
    movies: {},
    navigateTitle: "",
    requestUrl:"",
    totalCount:0,
    isEmpty:true,
  },
  onLoad: function(options) {
    //从父级传过来的数据
    var category = options.category;
    this.data.navigateTitle = category;
    console.log(category);
    var dataUrl = ""
    //点击那个more加载那个more页面的数据
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase +
          "/v2/movie/in_theaters";
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase +
          "/v2/movie/coming_soon";
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250";
        break;
    }
    //把dataUrl的值赋给requestUrl
    this.data.requestUrl = dataUrl;
    util.http(dataUrl, this.processDoubanData)
  },
  
  //下拉刷新数据
  onScrollLower:function(event){
     var nextUrl = this.data.requestUrl + "?start" + this.data.totalCount + "&count=20";
     //每次取20条数据
     util.http(nextUrl, this.processDoubanData)
    //加载数据显示加载中
    /*下拉刷新*/
    /*wx.showNavigationBarLoading()*/
    /*上拉刷新*/
    wx.showNavigationBarLoading()
  },
  
  //框架触发该函数
  onPullDownRefresh:function(event){
    var refreshUrl = this.data.requestUrl + "?start" + this.data.totalCount + "&count=20";
    this.data.movies = {};
    this.data.isEmpty = true;
    this.data.totalCount = 0;
    util.http(refreshUrl, this.processDoubanData)
    wx.showNavigationBarLoading()
  },

  //处理豆瓣数据
  processDoubanData: function (moviesDouban) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        //星星组件
        //stars: util.convertToStarsArray(subject.rating.stars),
        //标题
        title: title,
        //评分
        average: subject.rating.average,
        //海报
        coverageUrl: subject.images.large,
        //电影序号
        movieId: subject.id
      }
      //把temp推到movies数组里
      movies.push(temp);
    }
    var totalMovies = {}
    if(!this.data.isEmpty){
      totalMovies = this.data.movies.concat(movies);
    } else {
      totalMovies = movies
      this.data.isEmpty = false;
    }
    this.setData({
      movies: totalMovies
    });
    this.data.totalCount += 20;
    //隐藏数据加载中
    wx.hideNavigationBarLoading();
    //停止下拉数据加载中
    wx.stopPullDownRefresh();
  },

  onReady: function() {
    //动态显示导航标题
    wx.setNavigationBarTitle({
      title: this.data.navigateTitle
    });
    wx.showNavigationBarLoading()
  },

   //跳转详情页
   onMovieTap: function (event) {
    //电影的id序号
    var movieId = event.currentTarget.dataset.movieid
    wx.navigateTo({
      url: "../movie-detail/movie-detail?id="+movieId
    })
  },
})